import { useRef, useState } from 'react'
import { getAirplaneInfo, getAirplane, getAirplaneRecord, buyTicket } from '../../../api/active'
import './index.less'
import React, { useEffect } from 'react'
import { InfiniteScroll, Input, Modal, NoticeBar, Toast } from 'antd-mobile'
import { GetUserInfo } from '../../../api/mine'
import { compareVersions, getVersion, isIOS, unZipLottieFile } from '../../../utils/util'
import Lottie from 'lottie-web'
import appSdk from '../../../utils/app_sdk'
import { useNavigate } from 'react-router-dom'

let isDown = false

export default function AirplanePlace() {
  const navigate = useNavigate()
  const [activeInfo, setActiveInfo] = useState([])
  const [tickInfo, setTickInfo] = useState({})
  const [userinfo, setUserinfo] = useState({ mizuan: 0 })

  const [buyNum, setBuyNum] = useState(1)
  const [buyModalVisible, setBuyModalVisible] = useState(false)
  const [rewardVisible, setRewardVisible] = useState(false)
  const [rewardData, setRewardData] = useState([])
  const [recordVisible, setRecordVisible] = useState(false)
  // const [noticeList, setNoticeList] = useState([]);
  const [ruleVisible, setRuleVisible] = useState(false)
  const [noMoneyVisible, setNoMoneyVisible] = useState(false)

  const [animation, setAnimation] = useState(false)
  const ref = useRef()

  const initData = () => {
    getAirplaneInfo().then((res) => {
      console.log(res.data)
      setActiveInfo(res.data.list.concat(res.data.list))
      if (res.data.list[0]) {
        setTickInfo(res.data.list[0])
      } else {
        Toast.show({
          content: '活动暂未开放'
        })
      }
    })
    GetUserInfo().then((res) => {
      setUserinfo(res.data)
    })
  }

  useEffect(() => {
    initData()
    initAnimation()
  }, [])

  useEffect(() => {
    if (!isIOS() && compareVersions(getVersion() || '1.0.0', '2.2.0') !== -1) {
      appSdk('setFullScreen', 1)
    }
  }, [])

  const initAnimation = () => {
    if (!ref?.current && !isDown) {
      isDown = true
      Toast.show({
        content: '加载中~',
        icon: 'loading',
        maskClickable: false,
        duration: 0
      })
      // unZipLottieFile('https://cdn.aimengtec.com/h5_static/airplane_main.zip').then(res => {
      // 	console.log(res);
      // 	ref.current = Lottie.loadAnimation({
      // 		container: document.getElementById("lottie"),
      // 		renderer: "svg",
      // 		loop: false,
      // 		autoplay: false,
      // 		// 这里要修改为这个
      // 		assetsPath: `blob:${window.location.origin}/`,
      // 		animationData: res.json,
      // 	});
      // 	ref.current.addEventListener('complete', (r) => {
      // 		console.log('complete', r);

      // 		setRewardVisible(true)
      // 		// getRecordList();
      // 		setAnimation(false); // 结束
      // 		// setTimeout(() => {
      // 		Lottie.stop();
      // 		// }, 100);
      // 	});
      // 	setTimeout(() => {
      // 		Toast.clear()
      // 	}, 200);
      // }).catch(() => {
      // 	Toast.show({
      // 		content: '加载动画资源失败~',
      // 		icon: 'none'
      // 	})
      // })
    }
  }

  const buyTicketFun = () => {
    if (+userinfo.mizuan >= +tickInfo.ticket_mizuan * +buyNum) {
      buyTicket({
        ticket_id: tickInfo.ticket_id,
        nums: buyNum
      }).then((res) => {
        setBuyModalVisible(false)
        setBuyNum(1)
        initData()
        Toast.show({
          content: '购买成功',
          icon: 'success'
        })
      })
    } else {
      console.log('钱不够了')
      setBuyModalVisible(false)
      // setIsNoMoney(true)
      setNoMoneyVisible(true)
    }
  }

  // 抽奖
  const toBuy = (item, idx) => {
    setTickInfo(item)
    console.log('抽奖', item)
    if (+item.ticket_num === 0) {
      setBuyModalVisible(true)
      return false
    }
    if (+item.ticket_num < 10 && idx) {
      setBuyModalVisible(true)
      return false
    }
    if (+item.ticket_num > 0) {
      if (!animation) {
        Toast.show({
          content: '准备探索',
          icon: 'loading',
          maskClickable: false
        })
        getAirplane({
          box_id: item.id,
          nums: idx ? 10 : 1
        })
          .then((res) => {
            setAnimation(true)
            Lottie.play()
            console.log('抽出来的', res.data)
            setRewardData(res?.data)
            initData()
          })
          .finally(() => {
            Toast.clear()
          })
      } else {
        Toast.show({
          content: '等待探索结束~'
        })
      }
    } else {
      setBuyModalVisible(true)
    }
  }

  const [page, setPage] = useState(1)
  const [hasMore, setHasMore] = useState(true)
  const [recordList, setRecordList] = useState([])
  const getRecordList = async () => {
    try {
      const res = await getAirplaneRecord({ page })
      if (res.data && res.data?.length) {
        setRecordList(page === 1 ? res.data : recordList.concat(res.data))
      }
      if (res.data && res.data?.length >= 10) {
        setPage(page + 1)
        setHasMore(true)
      } else {
        setHasMore(false)
      }
    } catch {
      setHasMore(false)
    }
  }

  useEffect(() => {
    if (recordVisible) {
      setPage(1)
      setHasMore(true)
      setRecordList([])
    }
  }, [recordVisible])

  return (
    <div className="airpalne_wrap">
      <div className="content">
        <div className="close" onClick={() => appSdk('closeWebview')}></div>
        <div className="tips">
          <NoticeBar
            content={'理性参与游戏活动，禁止一切赌博性质行为，谨防上当受骗，杜绝违法犯罪，珍享游戏趣味。'}
            color="alert"
            icon={null}
          />
        </div>
        <div id="lottie"></div>
        <div className="btn-group">
          <div className="btn record" onClick={() => setRecordVisible(true)}></div>
          <div className="btn rule" onClick={() => setRuleVisible(true)}></div>
        </div>
        <div className="tick_group">
          <div className="num">
            {tickInfo?.ticket_name}剩余: {tickInfo?.ticket_num}
            <span
              onClick={() => {
                setTickInfo(activeInfo[0])
                setBuyModalVisible(true)
              }}
            >
              <span>兑换</span>
            </span>
          </div>
          <div className="group">
            {activeInfo.map((item, idx) => (
              <div className={`tick_item a_${idx}`} key={item.id + idx}>
                <div className={`btn b_${idx} `} onClick={() => toBuy(item, idx)}></div>
                <div className="tick_info">
                  <div className="icon">
                    <img src={item.ticket_img} alt="" />
                  </div>
                  <div className="name">
                    {item.ticket_name} x{idx ? 10 : 1}
                  </div>
                </div>
              </div>
            ))}
          </div>
        </div>

        <Modal
          visible={buyModalVisible}
          className="buy_tick"
          content={
            <div className="buy_info">
              <div className="name">{tickInfo?.ticket_name}兑换</div>
              <div className="img">
                <img src={tickInfo.ticket_img} alt="" />
              </div>
              <div className="input_content">
                <div className="down bt" onClick={() => setBuyNum(buyNum > 1 ? +buyNum - 1 : 1)}>
                  -
                </div>
                <div className="input">
                  <Input
                    onChange={(v) => {
                      if (v >= 9999) {
                        setBuyNum(9999)
                      } else {
                        setBuyNum(Number(v).toFixed(0).replace(/^0+/, ''))
                      }
                    }}
                    value={buyNum}
                    type="number"
                    min={1}
                    max={9999}
                  ></Input>
                </div>
                <div className="add bt" onClick={() => setBuyNum(buyNum < 9999 ? +buyNum + 1 : 9999)}>
                  +
                </div>
              </div>
              <div className="money">
                需要{Number(buyNum) * Number(tickInfo.ticket_mizuan)}
                {window.baseConfig.coin_name}
              </div>
              <div className="btn_group">
                <div className="cancel" onClick={() => setBuyModalVisible(false)}>
                  取消
                </div>
                <div className="buy" onClick={buyTicketFun}>
                  兑换
                </div>
              </div>
            </div>
          }
        ></Modal>

        <Modal
          visible={rewardVisible}
          onClose={() => setRewardVisible(false)}
          className={`gift_modal long_wrap`}
          closeOnMaskClick={true}
          destroyOnClose={true}
          content={
            <div className="gift_data">
              {/* <div className="gift_box_img"></div> */}
              <div className="box_tit">探索结果</div>
              <div className="price">
                价值：{rewardData?.price_count_nums || 0}
                {window.baseConfig.coin_name}
              </div>
              {/* ${rewardData.reward_data?.length} */}
              <div className={`gift_list`}>
                {rewardData.reward_data?.map((item) => (
                  <div className="item" key={item.id}>
                    {+item.nums > 1 ? <div className="nums">x{item.nums}</div> : null}
                    <img src={item.img} alt="" />
                    <div className="name ellipsis1">{item.name}</div>
                    <div className="item_price ellipsis1">{+item.price ? `${item.price}${window.baseConfig.coin_name}` : ''}</div>
                  </div>
                ))}
              </div>
            </div>
          }
        ></Modal>

        {/* 记录 */}
        <Modal
          closeOnMaskClick={true}
          onClose={() => setRecordVisible(false)}
          visible={recordVisible}
          className="record_modal"
          destroyOnClose
          content={
            <div>
              <RecordDetail recordList={recordList} getRecordList={getRecordList} hasMore={hasMore} />
            </div>
          }
        />

        <Modal
          closeOnMaskClick={true}
          onClose={() => setRuleVisible(false)}
          visible={ruleVisible}
          className="record_modal"
          destroyOnClose
          content={
            <div className="record">
              <div className="tit">星际探索活动规则</div>
              <div className="list cont">
                <p>
                  1、  “星际探索”活动分为初级探索和高级探索，初级探索每次花费50{window.baseConfig.coin_name}
                  ，每次探索后会随机出现1个探索奖励。高级探索每次花费500{window.baseConfig.coin_name}
                  ，每次探索后会随机出现10个探索奖励。出现的奖励可在可在"探索记录"里面查看。
                </p>
                <p>
                  2、  "星际探索"旨在提升聊天室娱乐的互动性，本互动功能中所获得道具均不可进行撤销、退款或退换，不可兑换成
                  {window.baseConfig.coin_name}、现金、不可再次交易; 您承诺不使用本功能进行任何违反法律法规及本平台规则、规范的活动或行为。
                </p>
                <p>
                  3、  利用漏洞或者是其他非法途径参与本活动，官方有权取消其活动参与资格。{window.baseConfig.package_name}
                  有权清除活动中的非法数据。
                </p>
                <p>4、  活动如有任何疑问请联系{window.baseConfig.package_name}客服。</p>
                <p>
                  5、  活动获得的所有虚拟道具及权益均不可进行转让、交易或变现，{window.baseConfig.package_name}
                  官方有权对任何违规行为进行处理。
                </p>
                <p>在此活动中，APPLE不是赞助者，也没有以任何形式参与活动</p>
                <p className="t">奖品详情</p>
                <div className="con">
                  <img src={tickInfo?.rule_img} alt="" />
                </div>
              </div>
            </div>
          }
        />

        {/* 余额不足提示弹窗 */}
        <Modal
          className={`no_monay_modal money`}
          onClose={() => setNoMoneyVisible(false)}
          visible={noMoneyVisible}
          closeOnMaskClick={false}
          content={
            <div className="">
              <div className="txt">{window.baseConfig.coin_name}不足是否进行充值</div>
              <div className="btn_group">
                <div className="cancel" onClick={() => setNoMoneyVisible(false)}>
                  取消
                </div>
                <div
                  className="buy"
                  onClick={() => {
                    navigate('/recharge')
                    setNoMoneyVisible(false)
                  }}
                >
                  同意
                </div>
              </div>
            </div>
          }
        ></Modal>
      </div>
    </div>
  )
}

export function RecordDetail({ recordList = [], getRecordList, hasMore }) {
  const [moreNote, setMoreNote] = useState('')
  return (
    <div className="record">
      <div className="tit">抽奖记录</div>
      <div className="list">
        {recordList.map((item) => (
          <div className="item_data" key={item.id}>
            <div
              className="item"
              onClick={() => {
                if (item.id === moreNote) {
                  setMoreNote(null)
                } else {
                  setMoreNote(item.id)
                }
              }}
            >
              <div className="info">
                <div className="name">
                  {item.box_name}x{item.nums}
                </div>
                <div className="time">{new Date(parseInt(item.create_time) * 1000).toLocaleString().replace(/:\d{1,2}$/, ' ')}</div>
              </div>
              <div className="note ellipsis1">{item.note}</div>
            </div>
            {moreNote === item.id ? <div className="more_note">{item.note}</div> : null}
          </div>
        ))}
        <InfiniteScroll loadMore={getRecordList} threshold={150} hasMore={hasMore} />
      </div>
    </div>
  )
}
